import React from 'react';
import { Bluetooth, BluetoothEvent, Device, Host, Package, Service } from "miot";
import LinearGradient from 'react-native-linear-gradient';
import Toast from 'react-native-root-toast';
import { AsyncStorage, View, Text, Image, TouchableOpacity, ImageBackground, ScrollView } from 'react-native';
import { TitleBar, LoadingDialog } from 'miot/ui';
import pxSize from './util/pxSize';
import TimeOut from './util/time';
import styles from './styles/MainPageStyl';

/**
 * SDK 提供的多语言 和 插件提供的多语言
 */
import { strings as SdkStrings, Styles as SdkStyles } from 'miot/resources';
import PluginStrings from '../resources/strings';
/**
 * SDK 支持的字体
 */
import * as SdkFontStyle from 'miot/utils/fonts';

/**
 * 插件开发者 争对 蓝牙设备说明文档， 需要对如下数据进行修改
 */
// console.log('SdkStrings :>> ', SdkStrings.addToDesktop);
const ServiceUUID = Bluetooth.UUID128('00000100-0065-6c62-2e74-6f696d2e696d');
const WCharacteristicUUID = Bluetooth.UUID128("00000101-0065-6c62-2e74-6f696d2e696d");
const NotifyCharacteristicUUID = Bluetooth.UUID128("00000102-0065-6c62-2e74-6f696d2e696d");

/**
 * 全局变量
 */
let bt = Device.getBluetoothLE();// 连接后的蓝牙对象
let timeing = undefined; // 定时器变量
let readOut = null;
let count = 0;// 读取次数计数
let startTime = true; // 计时器节流阀
let isBleConnected = true; // 点击开机是否扫描蓝牙
let conOn = false; // 连接侯开机
export default class MainPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      txtShowInfo: '',
      mac: '00:E0:12:34:56:79', // 蓝牙设备地址
      isEnable: "",
      timeIsShow: true, // 滚动时间显示隐藏
      timeSize: pxSize(250), // 圆的大小
      timeNumb: pxSize(40), // 数字大小
      timeUnit: pxSize(20), // 字的大小
      timeHeight: pxSize(500), // 运行时长上边距
      timeOpacity: 1, // 时间透明度
      themeColors: ["#F8F8F8", "#F8F8F8", "#F8F8F8"], // 背景渐变
      bleConnect: true, // 蓝牙连接中弹框
      shutDown: true, // 蓝牙连接时全部按钮是否禁用
      keepIsDisabled: false, // 关机后挡位按钮禁用
      on_off: true, // 开关机按钮
      keep_off_style: 0, // 挡位按钮点击添加样式
      time_h: '00', // 小时
      time_i: '00', // 分钟
      time_s: '00', // 秒
      power: '**', // 电量
      powerText: false,
      zigbee: true, // 设备是否连接网关
      isBleState: true // 蓝牙连接状态

    };
    this.initData();
    this.StartTime = '',
    this.ColseTime = '';

  }
  // 初始化数据
  initData() {
    this.keep_off = [// 开关按钮遍历
      {
        title: '1档',
        imgWhite: require('../resources/images/list_icon_gear1.png'),
        imgGray: require('../resources/images/list_icon_1.png')
      },
      {
        title: '2档',
        imgWhite: require('../resources/images/list_icon_gear2.png'),
        imgGray: require('../resources/images/list_icon_2.png')
      },
      {
        title: '3档',
        imgWhite: require('../resources/images/list_icon_gear3.png'),
        imgGray: require('../resources/images/list_icon_3.png')
      }
    ],
    this.backImg = {// 背景动图切换
      succeedImg: require('../resources/images/succeed.gif'),
      stopLinkImg: require('../resources/images/link.gif'),
      connectImg: require('../resources/images/link.gif')
    };
  }

  UNSAFE_componentWillMount() { // 页面渲染时加载
    if (bt && bt.isConnected) {
      bt.disconnect();
    }
    this.judgeBleOnOff(); // 判断手机蓝牙是否打开并扫描蓝牙
  }
  // 断开移除蓝牙监听事件
  componentWillUnmount() {
    this.removeBle();
    console.log("btbtbtbt", bt);
    AsyncStorage.removeItem('StartTime');
    AsyncStorage.removeItem('ColseTime');
    AsyncStorage.removeItem('StartBoole');
    AsyncStorage.removeItem('ColseBoole');
    AsyncStorage.removeItem('writeStringStart');
    AsyncStorage.removeItem('writeStringColse');
    clearInterval(timeing);

  }

  render() {
    return (
      <LinearGradient colors={this.state.themeColors} style={{ flex: 1 }}>
        <LoadingDialog
          visible={this.state.visible}
          message="蓝牙连接中，请稍后..."
        />
        <View style={styles.container}>
          <TitleBar
            type="dark"
            title={this.state.timeIsShow ? '除醛机' : `${ this.state.time_h }:${ this.state.time_i }: ${ this.state.time_s }`}
            style={{ height: pxSize(65), backgroundColor: "rgba(0, 0, 0, 0)" }}
            onPressLeft={() => { Package.exit(); }}
            onPressRight={() => { this.props.navigation.navigate('SettingPage', { 'title': '设置' }); }}
            showDot={this.state.showDot}
          />
          {/* 电池电量 */}

          {this.state.bleConnect ?
            null
            :
            (<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: "center", marginTop: pxSize(5), marginRight: pxSize(8), position: "absolute", top: pxSize(90), right: pxSize(20) }}>
              <Image resizeMode="contain" source={require('../resources/images/power_.png')} style={{ width: pxSize(18) }}></Image>
              <Text style={{ color: "#000000", marginLeft: pxSize(3), fontSize: pxSize(13) }}> {`${ this.state.power }%`} </Text>
            </View>)
          }

          <ScrollView scrollEventThrottle={1} onScroll={(event) => { this.scrollEvent(event); }} contentContainerStyle={styles.contentContainerStyle}>

            {/* 时间页面 */}
            {/* <TouchableOpacity onPress={()=>{(Host.isAndroid ? NativeModules.MIOTHost : NativeModules.MHPluginSDK).openBleOtaDeviceUpgradePage({ auth_type: 4 })}}> */}
            <View style={[{ height: pxSize(500), justifyContent: 'center', flexDirection: 'column', alignItems: 'center' }]}>{/* this.backImg.stopLinkImg */}
              {this.state.timeIsShow ?
                <ImageBackground source={this.state.bleConnect ? this.backImg.connectImg : (this.state.isBleState ? this.backImg.succeedImg : this.backImg.stopLinkImg)}
                  style={{ opacity: this.state.timeOpacity, height: this.state.timeSize, width: this.state.timeSize, borderRadius: 100, flexDirection: "column", justifyContent: 'center', alignItems: 'center' }}>
                  {this.state.bleConnect ?
                    <Image resizeMode="contain" source={require("../resources/images/home_icon_link.png")}
                      style={{ flexDirection: 'row', height: pxSize(50), marginBottom: pxSize(7) }}></Image>
                    :
                    <View style={{ flexShrink: 0, flexDirection: 'row' }} >
                      <Text style={[styles.time_numb, { fontSize: this.state.timeNumb }]}>{this.state.time_h}<Text style={[styles.time_unit, { fontSize: this.state.timeUnit }]}>h</Text></Text>
                      <Text style={[styles.time_numb, { fontSize: this.state.timeNumb }]}>{this.state.time_i}<Text style={[styles.time_unit, { fontSize: this.state.timeUnit }]}>m</Text></Text>
                      <Text style={[styles.time_numb, { fontSize: this.state.timeNumb }]}>{this.state.time_s}<Text style={[styles.time_unit, { fontSize: this.state.timeUnit }]}>s</Text></Text>
                    </View>
                  }
                  <View style={{ flexDirection: "row", justifyContent: "center" }}>
                    <Text style={{ fontSize: this.state.timeUnit, color: '#fff', marginTop: pxSize(0), opacity: 0.6 }}>{this.state.bleConnect ? "连接中..." : "运行时长"}</Text>
                  </View>

                </ImageBackground>
                : null}
              {/* 电量过低 */}
              {
                this.state.power !== '**' && this.state.power.toString() && this.state.power < 20 ?
                  (<View style={[{ flexDirection: 'row', alignItems: 'center', justifyContent: "center", marginTop: pxSize(5), marginRight: pxSize(8) }, this.state.powerText ? { position: "absolute", top: pxSize(300) } : null]}>
                    <Image resizeMode="contain" source={require('../resources/images/home_icon_power.png')} style={{ width: pxSize(16) }}></Image>
                    <Text style={{ color: "#F5A529", marginLeft: pxSize(6), fontSize: pxSize(16) }}>电量过低</Text>
                  </View>)
                  :
                  null
              }

            </View>
            {/* </TouchableOpacity> */}

            {/* 控制模块 */}
            <View style={[this.state.zigbee ? { height: pxSize(500) } : { height: pxSize(600) }, { width: "100%" }]}>
              {/* 无连接网关提示 */}
              {
                this.state.zigbee ?
                  null
                  :
                  <TouchableOpacity onPress={() => { this.props.navigation.navigate('CQJWebView'); }}>
                    <View style={styles.on_off}>
                      <View style={[{ backgroundColor: "#C8D4FF", height: pxSize(50), width: pxSize(50), borderRadius: pxSize(25), marginLeft: pxSize(35), justifyContent: "center", alignItems: "center" }]}>
                        <Image resizeMode="contain" style={{ height: pxSize(25) }} source={require('../resources/images/lanya.png')}></Image>
                      </View>
                      <View style={{}}>
                        <Text style={{ marginLeft: pxSize(15), fontSize: pxSize(20), color: '#181818', fontWeight: '600' }}>未找到蓝牙网关</Text>
                        <Text style={{ marginTop: pxSize(3), marginLeft: pxSize(15), fontSize: pxSize(17), color: '#cccccc' }}>可能设备与蓝牙网关距离太远</Text>
                      </View>
                      <Image source={require('../resources/images/next_step.png')} style={{ height: pxSize(26), width: pxSize(26), position: "absolute", right: pxSize(35) }}></Image>
                    </View>
                  </TouchableOpacity>
              }

              {/* 开关按钮 */}

              <View style={styles.on_off}>
                <TouchableOpacity onPress={() => { this.startOrClose(); }} style={[{ height: pxSize(50), width: pxSize(50), borderRadius: pxSize(25), marginLeft: pxSize(35), justifyContent: "center", alignItems: "center" }
                  , this.state.on_off ? { backgroundColor: '#F86A3D' } : { backgroundColor: "#26ABF6" }
                ]}>
                  <Image resizeMode="contain" style={{ height: pxSize(25) }} source={require('../resources/images/list_icon_switch1.png')}></Image>
                </TouchableOpacity>
                {
                  this.state.on_off ?
                    <Text style={{ marginLeft: pxSize(15), fontSize: pxSize(17), color: '#181818' }}>关机</Text>
                    :
                    <Text style={{ marginLeft: pxSize(15), fontSize: pxSize(17), color: '#181818' }}>开机</Text>
                }
              </View>

              {/* 点击选档 */}
              <View style={styles.click_change} >
                {/* 档 */}
                {this.keep_off.map((item, index) => {
                  return (
                    <View style={styles.click_item} key={index}>
                      <TouchableOpacity disabled={this.state.shutDown || this.state.keepIsDisabled} onPress={() => { this.keep_off_change(index); }} style={
                        [
                          styles.buttonStyle
                          , this.state.keep_off_style === index ? { backgroundColor: '#26ABF6', borderColor: 0 } : null
                          , this.state.shutDown && this.state.keep_off_style === index || this.state.keep_off_style === index && this.state.keepIsDisabled ? { backgroundColor: '#ccc' } : null
                        ]}>
                        {this.state.keep_off_style === index ?
                          <Image resizeMode="contain" style={{ height: pxSize(30) }} source={item.imgWhite}></Image>
                          :
                          <Image resizeMode="contain" source={item.imgGray} style={{ height: pxSize(30) }}></Image>}
                      </TouchableOpacity>
                      <Text style={[styles.click_title
                        , !this.state.bleConnect
                          ? { color: '#808080' }
                          : null
                        , this.state.keep_off_style === index && !this.state.keepIsDisabled && !this.state.shutDown
                          ? { color: '#26ABF6' }
                          : null

                      ]}>{item.title}</Text>
                    </View>
                  );
                })}
              </View>
              {/* 定时开关机 */}

              <TouchableOpacity activeOpacity={.7} disabled={this.state.shutDown || this.state.keepIsDisabled} onPress={() => { this.props.navigation.navigate('TimeSetUpPage'); }} >
                <View style={[styles.on_off, { marginBottom: pxSize(15) }]}>
                  <View style={[{ justifyContent: "center", alignItems: "center", backgroundColor: "#26ABF6", height: pxSize(50), width: pxSize(50), borderRadius: pxSize(25), marginLeft: pxSize(35) }
                    , this.state.shutDown || this.state.keepIsDisabled ? { backgroundColor: '#ccc' } : null
                  ]}>
                    <Image resizeMode="contain" source={require('../resources/images/list_icon_timing1.png')} style={{ height: pxSize(25) }}></Image>
                  </View>
                  <View style={{ marginLeft: pxSize(15) }}>
                    <Text style={{ fontSize: pxSize(17), color: '#181818' }}>定时开关机</Text>

                  </View>

                  <Image source={require('../resources/images/next_step.png')} style={{ height: pxSize(26), width: pxSize(26), position: "absolute", right: pxSize(35) }}></Image>

                </View>
              </TouchableOpacity>

            </View>

          </ScrollView>

        </View>
      </LinearGradient>
    );
  }


  addLog(title) {
    console.log(title);
  }
  // 监听屏幕滚动
  scrollEvent(event) {
    let scrollY = event.nativeEvent.contentOffset.y;
    let bili = (100 - scrollY) / 100;
    if (Host.isAndroid) {
      if (scrollY < 0) {
        this.setState(() => {
          return {
            timeSize: pxSize(250),
            timeNumb: pxSize(40),
            timeUnit: pxSize(20),
            timeHeight: pxSize(500),
            timeOpacity: 1
          };
        });
      } else {
        this.setState(() => ({
          timeSize: pxSize(250 - scrollY * 2),
          timeNumb: pxSize(40 * bili),
          timeUnit: pxSize(20 * bili),
          timeHeight: pxSize(500 * bili),
          timeOpacity: bili
        })

        );
      }
    }
    this.setState(() => ({
      timeOpacity: bili
    })
    );
    if (scrollY >= 60) {
      this.setState(() => ({ timeIsShow: false }));
    }
    if (scrollY <= 1) {
      this.setState(() => ({ timeIsShow: true }));
    }
    if (scrollY >= 166) {
      this.setState(() => ({
        powerText: true
      }));
    } else {
      this.setState(() => ({
        powerText: false
      }));
    }

  }
  // 消息提示弹框
  showPop(title) {
    Toast.show(title, {
      duration: Toast.durations.SHORT,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0
    });
  }
  // 点击换挡事件
  keep_off_change(index) {
    this.setState(() => ({ keep_off_style: index }));
    this.connectMac(index);// 触发事件
  }
  // 关机和开机事件
  startOrClose() {
    if (this.state.on_off) { // 关机操作
      this.setState(() => ({
        time_h: "00",
        time_i: "00",
        time_s: "00"
      }));
      conOn = true; // 下次开机连接成功后自动写入开机
      clearInterval(timeing);
      MainPage.bleWrite('B851020000008B');
      clearInterval(readOut);
      // bt.disconnect();
      startTime = true;
     
      
    } else {
      if (isBleConnected) {
        MainPage.bleWrite('B851010000008B');
        this.startScan();
      } else {
        MainPage.bleWrite('B851010000008B');
        isBleConnected = true;
      }
      
    } // true关机 , false开机
  
    this.setState(() => ({
      on_off: !this.state.on_off,
      keepIsDisabled: !this.state.keepIsDisabled
    }));
  }
  // 模拟开始运行 , 开启定时器，计算运行时间
  startTimer(new_time) {
    clearInterval(timeing);
    console.log('object :>> ', new_time);
    let second = new_time;
    timeing = setInterval(() => {
      second++;
      console.log('second', second);
      const time_obj = TimeOut.presentTime(second);
      this.setState(() => ({
        time_h: time_obj.h,
        time_i: time_obj.i,
        time_s: time_obj.s
      }));
      // console.log('clearTimer', timeing);
    }, 1000);
  }


  /**
 * 
 * @param {boolean} parma 
 */
  // notify的方法
  bleNotify(parma) {
    parma ? console.log('开始setNotify已开启') : console.log('开始setNotify已关闭');
    bt.getService(ServiceUUID).getCharacteristic(NotifyCharacteristicUUID).setNotify(parma)
      .then((ble) => {
        count++;
        console.log(` setNotify监听 已开启`, ble, count);
      })
      .catch((error) => {
        let info = `开始setNotify error...${ JSON.stringify(error) }`;
        console.log(info);
      });
  }


  /**
   * @param {string} value  //写入的值
   */
  // 写数据的方法

  static bleWrite(value) {

    console.log('session加密后返回的promise', bt.securityLock.encryptMessage(value));
    bt.securityLock.encryptMessage(value).then((hex) => {
      console.log(`session加密成功: ${ JSON.stringify(hex) }`);
      bt.getService(ServiceUUID).getCharacteristic(WCharacteristicUUID).writeWithoutResponse(hex).then((res) => {
        this.addLog(`写入成功: ${ JSON.stringify(res) }`);
      })
        .catch((err) => {
          console.log(`写入失败: ${ JSON.stringify(err) }`);
        });
    });

  }

  /**
   * @param {int} index // 点击读取时传入的按钮索引
   */
  // 换档时 点击对特征值读写操作
  connectMac(index) {
    console.log(this.state.mac);
    if (index === 0) { MainPage.bleWrite('B850030000008B'); }// B850010000008B
    if (index === 1) { MainPage.bleWrite('B850020000008B'); }// B850020000008B
    if (index === 2) { MainPage.bleWrite('B850010000008B'); }// B850030000008B

  }
  /**
 * 
 * @param {String} props  ObjId  电量:4106  运行时间:4114
 */
  // 获取网关数据
  getSmarthome(prop) {
    console.log('day', Math.round(Date.now() / 1000 / 3600 / 24 / 365));
    if (prop == '4114') {
      Service.smarthome.getDeviceData({
        did: Device.deviceID,
        type: "prop",
        key: prop,
        time_start: 0,
        time_end: Math.round(Date.now() / 1000)
      }).then((res) => {
        console.log('获取网关上的运行时间  成功', res);
        let off_on = JSON.parse(res[0].value)[0]; // 开关机状态
        console.log("getSmarthome -> off_on", off_on);
        if (off_on == "02") {
          this.showPop("设备已关机");
        } else if (off_on == "01") {
          this.showPop("设备运行中");
          let second = Date.now() / 1000 - res[0].time; // 运行总秒数
          this.startTimer(second);

        }
      }).catch((err) => {
        console.log('获取网关上的运行时间  失败', err);
      });
    } else if (prop == '4106') {
      Service.smarthome.getDeviceData({
        did: Device.deviceID,
        type: "prop",
        key: prop,
        time_start: 0,
        time_end: Math.round(Date.now() / 1000)
      }).then((res) => {
        console.log('获取网关上的设备电量  成功', res);
        let power = parseInt(JSON.parse(res[0].value)[0].substr(0, 2)); // 设备电量
        console.log("getSmarthome -> power", power);
        this.setState({
          power: power // 电量
        });
      }).catch((err) => {
        console.log('获取网关上的设备电量  失败', err);
      });
    }
  }
  /* static setStateTime(){ //设置获取时间
     this.setState({
       startTime:true
     })
     console.log('setStateTime 出发了 ');
   } */
  // 判断手机蓝牙是否打开
  judgeBleOnOff() {
    this.bleListener();
    Bluetooth.checkBluetoothIsEnabled().then((result) => {
      this.setState(() => ({
        isEnable: result
      }));

      if (result) {
        this.addLog("蓝牙已开启");
        setTimeout(() => {
          Bluetooth.isBleGatewayConnected(this.state.mac).then((res) => {
            console.log('是否连接网关', res);
            if (this.state.bleConnect) {
              if (res === 0 || res === true) {
                this.showPop("网关已连接");
                console.log(' ');
                this.setState({
                  zigbee: true,
                  bleConnect: false
                });
                this.getSmarthome('4114');
                this.getSmarthome('4106');
              } else {
                this.showPop("设备未连接网关");
                console.log('没连接网关');
                this.setState({
                  zigbee: false
                });
              }
            }

          });
        }, 10000);
      } else {
        this.addLog("蓝牙未开启，请检查开启蓝牙后再试");
        Host.isAndroid ? Bluetooth.enableBluetoothForAndroid(true) : Host.ui.showBLESwitchGuide();
      }
      this.startScan();// 扫描指定设备

    });
  }
  // 扫描蓝牙
  startScan() {
    console.log("开始扫描蓝牙");
    Bluetooth.startScan(30000, 'FE95');// Bluetooth.startScan(30000, 'FE95','FE96');//扫描指定设备
    this.showPop("设备扫描中");
  }
  // ios手动开始发现特征值
  startDiscoverCharacteristics() {
    if (bt && bt.getService(ServiceUUID)) {
      console.log('ios手动开始发现特征值');
      bt.getService(ServiceUUID).startDiscoverCharacteristics();
    }
  }
  // 连接蓝牙
  connect() {
    clearInterval(readOut);
    console.log("准备开始蓝牙连接");
    this.setState({
      visible: true
    });
    if (bt.isConnected) {
      console.log("蓝牙设备已经连接,开始发现服务");
    } else if (bt.isConnecting) {
      console.log("蓝牙正处于连接中，请等待连接结果后再试");
    } else {
      bt.connect(4, { did: Device.deviceID }).then((data) => {
        if (conOn) {
          MainPage.bleWrite('B851010000008B');
        }
        console.log("蓝牙连接成功: ", data);
        console.log("蓝牙设备已经连接,开始发现服务");
        this.showPop("连接成功");
        // 切换ui状态
        this.setState(() => ({
          visible: false,
          bleConnect: false,
          shutDown: false
        }));

        if (Host.isIOS) {
          console.log("isIOS开始手动发现Services");
          bt.startDiscoverServices();
        } else {     
          MainPage.bleWrite('B852000000008B');
        }
        readOut = setInterval(() => {
          MainPage.bleWrite('B852000000008B');
        }, 5000);
       
      }).catch((data) => {
        this.setState(() => ({
          visible: false
        }));
        this.showPop('蓝牙连接失败');
        console.log("蓝牙连接失败: ", data);
        this.showPop("无法找到设备,请退出重新连接");
      });
    }
  }

  // 蓝牙监听事件
  bleListener() {
    // 蓝牙设备扫描发现事件
    this._s1 = BluetoothEvent.bluetoothDeviceDiscovered.addListener((result) => {

      // 普通蓝牙设备的连接必须在扫描到设备之后手动创建 ble 对象
      /*  let name = '';
      Host.isAndroid ? name = result.name : name = result.peripheral.name;
      console.log('name', name);  */
      // if (name === "YM Formaldehyde purifier" || name === "YM_Formaldehyde_purifier") {
      console.log("初次发现设备", JSON.stringify(result));
      Bluetooth.stopScan();
      this.connect();
      /* } else {
        this.startScan();// 重新扫描蓝牙
      } */

    });
    // 蓝牙服务发现事件
    this._s2 = BluetoothEvent.bluetoothSeviceDiscovered.addListener((blut, services) => {
      console.log('services....', services);
      if (services) {
        services.forEach((service) => {
          if (service.UUID.toUpperCase()) {
            // 通过服务发现对应的特征值
            // Android 蓝牙连接成功后，会自动进行发现服务、特征值的操作, 因此无需再次调用发现特征值接口
            if (Host.isIOS) {
              console.log('我IOS手动发现特征值');
              this.startDiscoverCharacteristics(ServiceUUID);
            }
          }
        });
      }
    });
    // 蓝牙特征发现事件-成功
    this._s3 = BluetoothEvent.bluetoothCharacteristicDiscovered.addListener((bluetooth, service, characters) => {
      console.log("蓝牙特征值发现:", characters.map((s) => s.UUID), bt.isConnected);
      console.log(`当前连接的设备是${ bt.uuid }`);
      this.bleNotify(true);
      Host.isIOS ? MainPage.bleWrite('B852000000008B') : null;
    });
    // 蓝牙特征值变更事件
    this._s4 = BluetoothEvent.bluetoothCharacteristicValueChanged.addListener((bluetooth, service, character, value) => {
      if (service.UUID.indexOf('ffd5') > 0) {
        console.log('bluetoothCharacteristicValueChanged', character.UUID, value);// 刷新界面
      }
      if (character.UUID.toUpperCase() === NotifyCharacteristicUUID) {
        this.addLog(`收到原始回复：${ value }`);
        bt.securityLock.decryptMessage(value).then((res) => {
          this.addLog(`解密之后回复：${ res }`);
          let now_off = res.substr(4, 2); // 当前挡位开关机状态
          // 获取当前电量
          if (res.substr(12, 2) !== "ff") {
            console.log('截取挡位16进制', res.substr(12, 2));
            console.log('16转10,电量', parseInt(res.substr(12, 2), 16));
            this.setState(() => ({
              power: parseInt(res.substr(12, 2), 16)
            }));
          }
          if (now_off != 'ff') {
            console.log("当前挡位", now_off);
            if (now_off == '00') { // 关机
              isBleConnected = false; // 点击开机不扫描烂牙
              this.setState(() => ({
                on_off: false,
                keepIsDisabled: true,
                time_h: "00",
                time_i: "00",
                time_s: "00"
              }));
              clearInterval(timeing);
              startTime = true;
            } else if (now_off == '01') { // 三档
              this.setState(() => ({
                on_off: true,
                keepIsDisabled: false, keep_off_style: 2
              }));
            } else if (now_off == '02') { // 二档
              this.setState(() => ({
                on_off: true,
                keepIsDisabled: false, keep_off_style: 1
              }));
            } else if (now_off == '03') { // 一档
              this.setState(() => ({
                on_off: true,
                keepIsDisabled: false, keep_off_style: 0
              }));
            }
          }
          if (res.substr(6, 6) != 'ffffff' && now_off != '00' && startTime) {
            startTime = false;
            let now_time = parseInt(res.substr(6, 6), 16); // 获取运行时间
            this.state.on_off ? this.startTimer(now_time) : null; //  开启定时器
            console.log("运行总秒数", now_time);
          }

        });
      }
    });
    // 手机蓝牙开关状态变更事件
    this._s5 = BluetoothEvent.bluetoothStatusChanged.addListener((data) => {
      console.log('data', data);
      if (data) {
        startTime = true;
        this.startScan();
        console.log("蓝牙状态发生变化:", data);
        this.addLog("蓝牙已开启");
      } else {
        console.log("蓝牙状态发生变化:", data);
        this.addLog("蓝牙已关闭");
        this.setState(() => ({
          shutDown: true
        }));

      }
    });
    // 蓝牙服务发现失败事件
    this._s6 = BluetoothEvent.bluetoothSeviceDiscoverFailed.addListener((blut, data) => {
      console.log("服务发现失败:", data);
    });
    // 蓝牙特征发现事件-失败
    this._s7 = BluetoothEvent.bluetoothCharacteristicDiscoverFailed.addListener((blut, data) => {
      console.log("特征值发现失败:", data);
    });
    // 蓝牙连接状态改变的事件
    this._s8 = BluetoothEvent.bluetoothConnectionStatusChanged.addListener((blut, isConnect) => {
      console.log("蓝牙连接状态改变。。。。。:", blut, isConnect);

      if (!isConnect) {
        // 断开重连
        //  this.startScan()
        this.showPop("蓝牙断开");
        this.setState(() => ({
          shutDown: true
        }));
        clearInterval(timeing);
        this.setState(() => ({
          time_h: "00",
          time_i: "00",
          time_s: "00"
        }));
      }
      this.setState(() => ({
        isBleState: isConnect
      }));

    });
  }
  // 移除事件监听
  removeBle() {
    if (bt && bt.isConnected) {
      bt.disconnect();
    }
    console.log("disconnect");
    this._s1.remove();
    this._s5.remove();
    this._s8.remove();
    this._s6.remove();
    this._s7.remove();
    this._s2.remove();
    this._s3.remove();
    this._s4.remove();
    Bluetooth.stopScan();

  }
}





